#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
请求拦截相关的 API 路由
"""

import logging
from flask import Blueprint, request, jsonify
from db.mongo import get_db
from intercept.services.intercept_service import InterceptService
from intercept.services.ebpf_capture import EbpfCaptureService

# 尝试导入 libbpf 捕获服务
try:
    from intercept.services.libbpf_capture import LibbpfCaptureService
    LIBBPF_AVAILABLE = True
except ImportError:
    LIBBPF_AVAILABLE = False

logger = logging.getLogger(__name__)

# 创建蓝图
request_intercept_bp = Blueprint('request_intercept', __name__)

@request_intercept_bp.route('/start', methods=['POST'])
def start_intercept():
    """启动拦截服务"""
    try:
        data = request.json or {}
        service_id = data.get('service_id')
        direction = data.get('direction', 'both')
        
        if not service_id:
            return jsonify({"error": "缺少服务ID"}), 400
            
        # 获取服务信息
        service = InterceptService.get_intercept_service_by_id(service_id)
        if not service:
            return jsonify({"error": f"服务不存在: {service_id}"}), 404
            
        # 构建服务列表
        services = [{
            "service_id": str(service["_id"]),
            "service_name": service["service_name"],
            "service_ip": service["service_ip"],
            "service_port": service["service_port"],
            "direction": direction
        }]
        
        # 启动拦截服务
        # 如果可用，优先使用 libbpf (CO-RE) 方式
        if LIBBPF_AVAILABLE:
            logger.info("使用 libbpf (CO-RE) 方式启动拦截服务")
            success = LibbpfCaptureService.start_capture(services=services)
        else:
            # 使用 BCC 或模拟模式
            success = EbpfCaptureService.start_capture(services=services)
            
        if success:
            return jsonify({
                "message": f"拦截服务已启动，服务: {service['service_name']}，方向: {direction}",
                "service": service,
                "direction": direction,
                "is_running": True
            }), 200
        else:
            return jsonify({
                "message": "拦截服务已经在运行",
                "services": EbpfCaptureService.get_services(),
                "is_running": True
            }), 200
            
    except Exception as e:
        logger.error(f"启动拦截服务失败: {e}")
        return jsonify({"error": f"启动拦截服务失败: {str(e)}"}), 500
        
@request_intercept_bp.route('/stop', methods=['POST'])
def stop_intercept():
    """停止拦截服务"""
    try:
        # 停止拦截服务
        # 如果 libbpf 捕获服务正在运行，则停止它
        if LIBBPF_AVAILABLE and LibbpfCaptureService.is_running():
            logger.info("停止 libbpf 拦截服务")
            success = LibbpfCaptureService.stop_capture()
        else:
            # 停止 BCC 拦截服务
            success = EbpfCaptureService.stop_capture()
            
        if success:
            return jsonify({
                "message": "拦截服务已停止",
                "is_running": False
            }), 200
        else:
            return jsonify({
                "message": "拦截服务未在运行",
                "is_running": False
            }), 200
            
    except Exception as e:
        logger.error(f"停止拦截服务失败: {e}")
        return jsonify({"error": f"停止拦截服务失败: {str(e)}"}), 500
        
@request_intercept_bp.route('/status', methods=['GET'])
def get_intercept_status():
    """获取拦截服务状态"""
    try:
        # 如果 libbpf 捕获服务正在运行，使用它的状态
        if LIBBPF_AVAILABLE and LibbpfCaptureService.is_running():
            is_running = True
            services = LibbpfCaptureService.get_services()
        else:
            # 使用 BCC 捕获服务的状态
            is_running = EbpfCaptureService.is_running()
            services = EbpfCaptureService.get_services()
            
        return jsonify({
            "is_running": is_running,
            "services": services
        }), 200
        
    except Exception as e:
        logger.error(f"获取拦截服务状态失败: {e}")
        return jsonify({"error": f"获取拦截服务状态失败: {str(e)}"}), 500
        
@request_intercept_bp.route('/list', methods=['GET'])
def list_intercept_rules():
    """获取拦截规则列表"""
    try:
        # 获取拦截规则列表
        rules = InterceptService.get_intercept_rules()
        
        return jsonify({
            "rules": rules
        }), 200
        
    except Exception as e:
        logger.error(f"获取拦截规则列表失败: {e}")
        return jsonify({"error": f"获取拦截规则列表失败: {str(e)}"}), 500
